<?php
declare(strict_types=1);

namespace app\admin\controller\system;

use app\admin\model\AuthGroup as AuthGroupModel;
use app\admin\model\AuthRule as AuthRuleModel;
use app\admin\model\AuthRuleAccess as AuthRuleAccessModel;
use app\common\Attribute\ClassTitle;
use app\common\Attribute\RequestMethod;
use app\common\Attribute\RequestTitle;
use app\common\controller\AmisAdminController;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\exception\ValidateException;
use think\facade\Db;
use think\Request;
use LhpAmis\Renderers\Amis;
/**
 * 角色管理
 **/
#[ClassTitle(name: '角色')]
class AuthGroup extends AmisAdminController
{
    /**
     * 列表
     * @param \think\Request $request
     * @return \think\response\Json
     */
    #[RequestMethod(['GET,POST'])]
    #[RequestTitle('列表')]
    public function index(Request $request): \think\response\Json
    {
        if ($request->isPost()) {

            $start = (int) $request->param('start', 0);
            $limit = (int) $request->param('limit', 10);
            $order = $request->param('order', 'ASC');
            $wheres = [];
            $query = AuthGroupModel::where($wheres);
            $data = $query->limit($start, $limit)->order('create_time', $order)->paginate();

            return $this->data($data);
        }
        $amis = Amis::make()->TableBuilder()
            ->setTitle('列表')
            ->setSearchItems([
                ['title', '用户组中文名称'],
                ['description', '描述信息'],
                ['listorder', '排序ID', 'number'],
                ['create_time', '创建时间', 'date'],
                ['update_time', '更新时间', 'date'],
            ])
            ->addColumns([
                ['id', 'ID'],
                ['title', '用户组中文名称'],
                ['description', '描述信息'],
                ['listorder', '排序ID', 'number'],
                ['create_time', '创建时间', 'date'],
                ['update_time', '更新时间', 'date'],
                ['right_button', '操作', 'btn'],
            ])
            ->addTopButtons('create,delete')
            ->addRightButtons('edit,delete')
            ->addRightButtons([
                $this->rowCustomButton($this->BaseApiGet('access', ['id' => '${id}']), '授权'),
            ])
        ;
        return $this->data($amis);
    }

    /**
     * 创建
     * @param \think\Request $request
     * @return \think\response\Json
     */
    #[RequestMethod(['GET,POST'])]
    #[RequestTitle('创建')]
    public function create(Request $request): \think\response\Json
    {
        if ($request->isPost()) {
            $data = $request->all();
            try {
                $this->validate($data, [
                    'title' => 'require',
                ], [
                    'title.require' => '名称必须',
                ]);
            } catch (ValidateException $e) {
                return $this->error($e->getError());
            }
            $result = AuthGroupModel::create([
                'title' => $data['title'],
                'description' => $data['description'] ?? '',
                'listorder' => $data['listorder'] ?? 100,
            ]);
            if ($result->isEmpty()) {
                return $this->error('错误');
            }

            return $this->success('成功');
        }
        $amis = Amis::make()->FormBuilder()
            ->setTitle('创建')
            ->addFormItems([
                ['title', '用户组中文名称'],
                ['description', '描述信息'],
                ['listorder', '排序ID', 'number'],
            ])
            ->setSubmitAction();
        return $this->data($amis);
    }


    /**
     * 更新
     * @param string $id
     * @param \think\Request $request
     * @return \think\response\Json
     */
    #[RequestMethod(['GET,POST'])]
    #[RequestTitle('更新')]
    public function update(string $id, Request $request): \think\response\Json
    {
        if ($request->isPost()) {

            $data = $request->all();
            try {
                $authGroup = AuthGroupModel::where('id', $id)->find();
                if (!$authGroup) {
                    return $this->error('角色不存在');
                }
            } catch (DataNotFoundException | ModelNotFoundException | DbException $e) {
                return $this->error('角色不存在');
            }

            try {
                $this->validate($data, [
                    'title' => 'require',
                ], [
                    'title.require' => '名称必须',
                ]);
            } catch (ValidateException $e) {
                return $this->error($e->getError());
            }
            $result = $authGroup
                ->save([
                    'title' => $data['title'],
                    'description' => $data['description'] ?? '',
                    'listorder' => $data['listorder'] ?? 100,
                ]);
            if (!$result) {
                return $this->error('错误');
            }

            return $this->success('成功');
        }
        $amis = Amis::make()->FormBuilder()
            ->setTitle('创建')
            ->addFormItems([
                ['id', '用户组ID', 'hidden'],
                ['title', '用户组中文名称'],
                ['description', '描述信息'],
                ['listorder', '排序ID', 'number'],
            ])
            ->setSubmitAction();
        return $this->data($amis);
    }

    /**
     * 删除
     * @param string $id
     * @return \think\response\Json
     */
    #[RequestMethod(['DELETE'])]
    #[RequestTitle('删除')]
    public function delete(string $id): \think\response\Json
    {
        try {
            //code...

            $row = AuthGroupModel::where('id', $id)->find();
            if (!$row) {
                return $this->error('错误');
            }
            $row->delete();

            return $this->success('成功');
        } catch (\Throwable $th) {
            return $this->error('错误:' . $th->getMessage());
        }
    }
    /**
     * 授权
     * @param string $id
     * @param \think\Request $request
     * @throws \Exception
     * @return \think\response\Json
     */
    #[RequestMethod(['GET,POST'])]
    #[RequestTitle('授权')]
    public function access(string $id, Request $request): \think\response\Json
    {
        if ($request->isPost()) {
            $row = AuthGroupModel::make()->where('id', $id)->find();
            if ($row->isEmpty()) {
                return $this->error('信息错误');
            }
            $access = $request->post('access');

            Db::startTrans();
            try {
                // 删除
                AuthRuleAccessModel::where('group_id', $id)->delete();
                $access = explode(',', $access) ?: [];
                $install = [];
                foreach ($access as $itemId) {
                    $install[] = [
                        'group_id' => $id,
                        'rule_id' => $itemId,
                    ];
                }

                $res = (new AuthRuleAccessModel())->saveAll($install);
                if (empty($res)) {
                    Db::rollback();
                    return $this->error('授权失败!');
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return $this->error($e->getMessage());
            }

            return $this->success('成功');
        }

        $amis = Amis::make()->FormBuilder()
            // ->data($data)
            ->addFormItems([
                ['id', '用户组ID', 'hidden', '', $id],
                ['access', '授权', 'transfer', '', '', (string) url('getTreeOptions'), ['valueTpl' => '${parent}-${label}-${method}', "searchable" => true, "selectMode" => "tree",]],
            ])
            ->setSubmitAction();
        return $this->data($amis);
    }
    /**
     * 获取树结构选项
     * @return \think\response\Json
     */
    #[RequestMethod(['GET'])]
    #[RequestTitle('获取树结构选项')]
    public function getTreeOptions()
    {
        return $this->data(AuthRuleModel::getTreeOptions());
    }
}
